package com.spi.xxjob;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class ScheduleJobAspect {

    @Autowired
    private RedisTemplate redisTemplate ;

    @Autowired
    private RedissonClient redissonClient ;

    @Around("@annotation(com.spi.xxjob.ScheduleJob)")
    public void job(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature methodSignature = (MethodSignature)joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        ScheduleJob annotation = method.getAnnotation(ScheduleJob.class);
        String key = annotation.key();
        RLock lock = null ;
        try {
            long beginTime = System.currentTimeMillis();
            lock = redissonClient.getLock(key);
            if (lock.tryLock()){
                joinPoint.proceed();
                Thread.sleep(3000);
            }else {
                System.out.println("获取锁失败。。。");
                return;
            }
            long endTime = System.currentTimeMillis();
            System.out.println("任务执行耗时===" + (endTime - beginTime)/1000);
        }catch (Exception e){
            e.printStackTrace();
            System.out.println("进入到aop异常代码块" + e.getMessage());
            throw new RuntimeException(e.getMessage()) ;
        }finally {
            if (lock != null && lock.isLocked() && lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }
}
